import React from 'react';
import { YunxiaoIcon } from '@alife/devops-ui';
import { navigate } from 'utils/router';
import utils from 'utils';
import MemberList from 'components/memberList';
import TextAvatar from '@txdfe/at-text-avatar';
import { GROUP_ADMIN_ROLES, ENUM } from 'utils/constants.js';
import intl from '../../../../../locale';

export default class GroupNav extends React.Component {
  constructor(props) {
    super(props);
    // ?open_member_diaolog=true自动弹出成员面板
    const open_member_diaolog = utils.getUrlSearchParam('open_member_diaolog') || '';
    const states = GroupNav.getDerivedStateFromProps(props);
    this.state = {
      hiddenKeys: [],
      showMemberList: open_member_diaolog === 'true',
      ...states,
    };
  }

  static getDerivedStateFromProps(props) {
    const { projectInfo, isProjectInfoFetched } = (props.group && props.group.root) || {};
    if (!isProjectInfoFetched) {
      return {};
    }
    const pageInfo = (props.root && props.root.pageInfo) || {};
    if (!pageInfo.pathResource) {
      return;
    }
    // 若库为空，则隐藏以下tab 或者导入状态为failed(初始化空库状态failed不变，结合isExist进行判断)/started
    const isImportUnfinished =
      projectInfo.import_status === 'started' ||
      projectInfo.import_status === 'stopping' ||
      (projectInfo.import_status === 'failed' && pageInfo.pathResource.isExist === 'false');
    const hiddenKeys =
      isImportUnfinished || pageInfo.pathResource.isEmpty === 'true'
        ? ['merge', 'commits', 'mergerequest', 'branches', 'tags', 'security']
        : [];
    let hideMember = false;
    const extendable = !isImportUnfinished;
    if (projectInfo.import_status === 'started' || projectInfo.import_status === 'stopping') {
      hideMember = true;
    }
    // 在库内，状态是none、finished、failed，并且isExist==true时，并且有权限时，展示设置入口
    const hideSetting = !(
      ['none', 'finished', 'failed'].includes(projectInfo.import_status) &&
      pageInfo.pathResource.isExist === 'true'
    );
    return {
      hiddenKeys,
      hideMember,
      hideSetting,
      extendable,
    };
  }

  componentDidMount() {
    const active = this.getActiveKeyFromAssetsName();
    this.initSidebar(active);
  }

  componentDidUpdate(prevProps, prevState) {
    const prevAssetname = prevProps.root.pageInfo.assetsName;
    const nowAssetname = this.props.root.pageInfo.assetsName;

    if (
      prevState.hiddenKeys !== this.state.hiddenKeys ||
      prevState.hideMember !== this.state.hideMember ||
      prevState.hideSetting !== this.state.hideSetting ||
      prevProps.group.root.groupInfo.avatar_url !== this.props.group.root.groupInfo.avatar_url ||
      prevAssetname !== nowAssetname
    ) {
      const active = this.getActiveKeyFromAssetsName();
      this.initSidebar(active);
    }
  }

  initSidebar = (active) => {
    const { groupInfo } = (this.props.group && this.props.group.root) || {};
    const main = this.getMain();
    const extra = this.getExtra();
    const { pathResource } = window.FORCE;
    let groupName = '';
    try {
      groupName = pathResource.fullName.split('/').pop().replace(' ', '');
    } catch (error) {
      console.error(error);
    }

    groupName &&
      window.TB_NAVIGATION.initOrUpdateSidebar &&
      window.TB_NAVIGATION.initOrUpdateSidebar({
        header: {
          logoUseJsx: !groupInfo.avatar_url,
          logo:
            groupInfo.avatar_url || (
              <TextAvatar text={groupName.toUpperCase()} image={groupInfo.avatar_url} isCover />
            ) ||
            'https://img.alicdn.com/imgextra/i4/O1CN01W1NAtC1tzDzobMP9r_!!6000000005972-2-tps-122-122.png',
          name: groupName || 'demo-group',
        },
        active,
        main,
        extra,
        level: 2,
      });
  };

  getMain = () => {
    const { hiddenKeys } = this.state;
    const { pathResource } = window.FORCE;
    const { groupCount, mergeRequestCount } = pathResource;

    const dataSource = [
      {
        key: 'home',
        id: `/${pathResource.fullPath}`,
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="folder-line" />,
        },
        name: (
          <div className="nav-item">
            {intl.get({
              id: 'code-assets.containers.tab.SubgroupsAndDatabases',
              defaultMessage: '子组与库',
            })}
            {groupCount ? <span className="nav-item-badge">{groupCount}</span> : null}
          </div>
        ),
        onClick: this.handleClick,
      },
      {
        key: 'mergerequest',
        id: `/${pathResource.fullPath}/merge_requests`,
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="pull-request-line" />,
        },
        name: (
          <div className="nav-item">
            {intl.get({
              id: 'code-assets.containers.tab.MergeRequest',
              defaultMessage: '合并请求',
            })}
            {mergeRequestCount ? <span className="nav-item-badge">{mergeRequestCount}</span> : null}
          </div>
        ),
        onClick: this.handleClick,
      },
      {
        key: 'activity',
        id: `/${pathResource.fullPath}/activity`,
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="historyrecord-line" />,
        },
        name: intl.get({
          id: 'code-assets.containers.tab.SummaryInvestingComZa',
          defaultMessage: '动态',
        }),
        onClick: this.handleClick,
      },
    ];

    const shownDataSource = dataSource.filter((item) => {
      return hiddenKeys && !hiddenKeys.includes(item.key);
    });
    return shownDataSource;
  };

  getExtra = () => {
    const { pathResource } = window.FORCE;
    const { role, type } = pathResource;
    const { hideMember, hideSetting } = this.state;

    const shownDataSource = [];

    if (!hideMember && type !== ENUM.path_resource_type.PERSONAL_NAMESPACE) {
      shownDataSource.push({
        id: 'groupMembers',
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="member-line" />,
        },
        name: intl.get({ id: 'code-assets.containers.tab.Members', defaultMessage: '成员' }),
        onClick: this.handleClickOpenMemberList,
      });
    }
    if (!hideSetting && GROUP_ADMIN_ROLES.includes(role)) {
      shownDataSource.push({
        id: `/${pathResource.fullPath}/settings`,
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="setting-line" />,
        },
        name: intl.get({ id: 'code-assets.containers.projectTab.Set', defaultMessage: '设置' }),
        onClick: this.handleClick,
      });
    }

    return shownDataSource;
  };

  handleClickOpenMemberList = () => {
    this.setState({
      showMemberList: true,
    });
  };

  handleClick = (v) => {
    this.initSidebar(v.id);
    navigate(`${v.id}?source_type=Namespace`);
  };

  // 由资源名判断高亮哪个tab
  getActiveKeyFromAssetsName = () => {
    const { assetsName } = window.FORCE;
    const dataSource = this.getMain();
    const key = assetsName.replace('group', '').toLocaleLowerCase();
    let result;
    if (dataSource.some((item) => item.key === key)) {
      result = key;
    } else {
      switch (key) {
        case 'settings':
          result = 'settings';
          break;
        default:
          break;
      }
    }

    const activeId = dataSource.find((item) => item.key === result)?.id;
    return activeId;
  };

  renderMemberDialog = () => {
    const { pathResource } = window.FORCE;
    const { hideMember, showMemberList } = this.state;
    if (hideMember) {
      return null;
    }
    return (
      <MemberList
        pathResourceId={pathResource.id}
        pathResourceType="group"
        align="tr br"
        role={pathResource.role}
        visible={showMemberList}
        onClose={() => {
          this.setState({
            showMemberList: false,
          });

          utils.getUrlSearchParam('open_member_diaolog') &&
            window.history.replaceState({}, null, window.location.pathname);
        }}
      />
    );
  };

  render() {
    return <>{this.renderMemberDialog()}</>;
  }
}
